package com.suhe.ozon.http;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.suhe.ozon.consts.OzonConsts;
import com.suhe.ozon.entity.dto.PriceSyncDTO;
import com.suhe.ozon.entity.po.ClientPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *     商品价格同步
 * </p>
 *
 * @author liuning
 * @date 23:03 2024/1/20
 */
@Slf4j
public class PriceHttp {

    /**
     * 获取商品价格信息url
     */
    private final String GET_PRODUCT_PRICE_LIST_URL = "https://api-seller.ozon.ru/v4/product/info/prices";

    public Map<String, PriceSyncDTO> sync(ClientPO ozonClient, String lastId) throws IOException {
        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(GET_PRODUCT_PRICE_LIST_URL);
        httpPost.addHeader("Client-Id", ozonClient.getClientId());
        httpPost.addHeader("Api-Key", ozonClient.getSecretKey());
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Host", "api-seller.ozon.ru");
        final ImmutableMap<String, Object> params = ImmutableMap.of(
                 "filter",
                Collections.emptyMap()
//                ImmutableMap.of("visibility", "ALL") // 除了已归档以外的所有商品
                , "last_id", lastId == null ? "" : lastId
                , "limit", OzonConsts.HTTP_PAGE_LIMIT
        );
        StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(params));
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        final CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.error("接口请求失败");
        }
        String result = EntityUtils.toString(response.getEntity());
        final JSONArray prices = JSONUtil.parseObj(result).getJSONObject("result").getJSONArray("items");
        return prices.stream().collect(Collectors.toMap(p -> ((JSONObject)p).getStr("product_id"), p -> {
            final JSONObject priceInfo = ((JSONObject) p).getJSONObject("price");
            return new PriceSyncDTO()
                    .setMinPrice(priceInfo.getBigDecimal("min_price"))
                    .setAutoActionEnabled(priceInfo.getBool("auto_action_enabled"));
        }, (oldVal, newVal) -> newVal));
    }
}
